<template>
    <div class="bg-f2f3f5 min-w-100 leaveSpace">
        <div class="flex gap-20 justify-center mar-x-auto max-w-1200 pad-y-10" style="min-height: calc(100vh - 91px)">
            <div class="flex-5">
                <div class="backHome bg-white font-14 pad-10">
                    <router-link
                        to="/"
                        style="text-decoration: none; color: #1e9fff"
                    >
                        <span class="mar-r-10">&lt;</span>
                        <span>返回首页</span>
                    </router-link>
                </div>

                <div class="flex-1 pad-30 bg-white border-rad-5">
                    <div class="font-20 font-bold">{{ articleDetails.title }}</div>

                    <div class="flex justify-between align-center mar-t-20 font-14">
                        <div>
                            <span class="backHome mar-r-20 color-666666">{{ articleDetails.nickName ? articleDetails.nickName : articleDetails.username }}</span>

                            <div class="flex align-center">
                                <span class="author-info mar-r-20 color-666666">{{ articleDetails.nickName ? articleDetails.nickName : articleDetails.username }}</span>
                                <span class="mar-r-20 color-8a919f">{{ formatDatetime(articleDetails.createTime) }}</span>

                                <div class="flex mar-r-20 color-8a919f align-center">
                                    <SvgIcons iconClass="view_icon" class="font-22 mar-r-2" />
                                    <div>{{ articleDetails.viewerCount ?? 0 }}</div>
                                </div>

                                <div
                                    :class="'flex mar-r-20 align-center hoverClass cur-pointer ' + (isLike ? 'color-1e9fff' : 'color-8a919f')"
                                    @click="handleLikeCount()"
                                >
                                    <SvgIcons iconClass="like_icon" class="font-20 mar-r-3" />
                                    <div>{{ articleDetails.likeCount ?? 0 }}</div>
                                </div>
                            </div>
                        </div>

                        <div class="backHome flex flex-1 justify-between mar-t-20 font-16"
                            :style="{display: ((userInfo ? userInfo.id : '') === articleDetails.userId) ? 'none' : ''}"
                        >
                            <div v-if="!isLogin || !isFollow" class="follow flex-1 text-center h-30 bg-1e80ff color-white line-h-30 pad-y-5 border-rad-5 mar-r-15"
                                @click="handleFollow()"
                            >
                                关注
                            </div>

                            <div v-if="isFollow" class="noFollow flex justify-center align-center h-30 w-px-36 pad-y-5 border-rad-5 mar-r-15 defaultBorder"
                                @click="cancelFollowUser()"
                            >
                                <SvgIcons iconClass="follow_icon" class="font-26 color-999999" />
                            </div>

                            <div v-if="isFollow" class="sixin flex-1 text-center h-30 bg-f4f9ff color-1e80ff line-h-30 pad-y-5 border-rad-5 b-1-solid-b3d5ff "
                                @click="handlePrivateMessage()"
                            >
                                私信
                            </div>
                        </div>
                    </div>

                    <div class="mar-t-15 font-18">
                        <p>{{ articleDetails.abstract }}</p>
                    </div>

                    <div class="mar-t-20 font-16 previewContainer" v-html="articleDetails.content">
                    </div>
                </div>

                <div v-if="!isLogin" class="pad-30 bg-white border-rad-5 mar-t-10">
                    <h3>评论 0 </h3>

                    <div class="flex mar-t-40">
                        <div class="overflow-hidden h-40 w-px-40 radius-50 flex justify-center">
                            <img src="@/assets/images/defaultAvatar.png" class="w-100 h100 img-normal"/>
                        </div>

                        <div class="flex bg-f2f3f5 font-14 w-100 h-100 justify-center border-rad-5 align-center mar-l-15">
                            <div class="bg-1e80ff mar-r-10 h-24 color-white border-rad-5 flex justify-center align-center pad-5 cur-pointer guanzhu" @click="handleShowLoginDialog()">
                                <span>登录 / 注册</span>
                            </div>

                            <div>即可发布评论!</div>
                        </div>
                    </div>

                    <el-empty
                        v-if="commentList.length === 0"
                        :image-size="100"
                        description="暂无评论数据"
                    >
                    </el-empty>
                </div>

                <div v-else class="pad-30 bg-white border-rad-5 mar-t-10">
                    <CommentList
                        ref="articleCommentList"
                        :articleId="articleId"
                        :authorId="userId"
                    />
                </div>
            </div>

            <div class="author-info pos-s w-px-250 t-80 bg-white h100 pad-20 border-rad-5">
                <div class="flex align-center justify-center">
                    <div class="w-px-50 h-50 overflow-hidden radius-50 mar-r-15 flex justify-center align-center defaultBorder">
                        <img :src="getAvatar" class="w-100 h100 img-normal" />
                    </div>

                    <div>
                        <div class="font-16">{{ articleDetails.nickName ? articleDetails.nickName : articleDetails.username }}</div>
                        <div class="color-8a919f font-14 mar-t-5">{{ articleDetails.job ? articleDetails.job : '暂无职位' }}</div>
                    </div>
                </div>

                <div class="flex mar-t-20 justify-around font-16">
                    <div class="text-center">
                        <div>{{ articleDetails.articleCount }}</div>
                        <div class="color-8a919f font-14 pad-5">文章</div>
                    </div>

                    <div class="text-center">
                        <div>{{ articleDetails.viewerTotalCount }}</div>
                        <div class="color-8a919f font-14 pad-5">阅读</div>
                    </div>

                    <div class="text-center">
                        <div>{{ articleDetails.followCount }}</div>
                        <div class="color-8a919f font-14 pad-5">粉丝</div>
                    </div>
                </div>

                <div class="flex justify-center mar-t-20 font-16"
                    :style="{display: ((userInfo ? userInfo.id : '') === articleDetails.userId) ? 'none' : ''}"
                >
                    <div v-if="!isLogin || !isFollow" class="follow flex-1 cur-pointer text-center h-30 bg-1e80ff color-white line-h-30 pad-y-5 border-rad-5"
                        @click="handleFollow()"
                    >
                        关注
                    </div>

                    <div v-if="isFollow" class="noFollow flex cur-pointer justify-center align-center h-30 w-px-36 pad-y-5 border-rad-5 mar-r-15 defaultBorder"
                        @click="cancelFollowUser()"
                    >
                        <SvgIcons iconClass="follow_icon" class="font-26 color-999999" />
                    </div>

                    <div v-if="isFollow" class="sixin flex-1 cur-pointer text-center h-30 bg-f4f9ff color-1e80ff line-h-30 pad-y-5 border-rad-5 b-1-solid-b3d5ff "
                        @click="handlePrivateMessage()"
                    >
                        私信
                    </div>
                </div>
            </div>
        </div>
        <Login
            :captchaId="captchaId"
            :captchaSvg="captchaSvg"
            :dialogVisible="dialogVisible"
            @cancelLoginDialog="cancelLoginDialog"
        />
    </div>
</template>

<script>
    import Lines from '@/components/Lines/index'
    import Login from '@/components/Login/index'
    import SvgIcons from '@/components/SvgIcons/index'
    import CommentList from '@/components/CommentList/index'
    import Utils from '@/utils/utils'
    import moment from 'moment'
    import 'moment/locale/zh-cn'

    import { mapState } from 'vuex'
    import { getCaptcha, follow, cancelFollow, findFollowState } from '@/apis/user'
    import { addViewCount, commentArticle, getCommentList, delComment, getLikeArticleState, likeArticle } from '@/apis/article'

    export default {
        name: "Details",

        props:{
        },

        components: {
            Lines,
            SvgIcons,
            Login,
            CommentList,
        },

        computed: {
            ...mapState({
                isLogin: state => state.user.isLogin, // 当前用户是否登录
                userInfo: state => state.user.userInfo, // 当前用户信息
                defaultAvatar: state => state.user.defaultAvatar, // 默认头像
                friendList: state => state.user.friendList, // 好友列表
                currentFriend: state => state.user.currentFriend, // 当前好友
                noReadMsgList: state => state.user.noReadMsgList, // 未读消息列表
            }),

            // 获取头像
            getAvatar() {
                return this.articleDetails.avatar ? process.env.VUE_APP_IMG_BASE_API + this.articleDetails.avatar : this.defaultAvatar
            },

            // 格式化当前时间
            formatDatetime() {
                return (dateTime) => {
                    if (!dateTime) return '';
                    
                    const now = moment();
                    const targetTime = moment(dateTime);
                    
                    // 如果时间差小于60秒，显示"刚刚"，否则使用fromNow
                    return now.diff(targetTime, 'seconds') < 60 ? '刚刚' : targetTime.fromNow();
                }
            },
        },

        data() {
            return {
                loading: false, // 加载中
                pageLoading: false, // 页面加载中
                captchaId: '', // 验证码id
                captchaSvg: '', // 验证码
                articleId: '',  // 文章id
                userId: '', // 文章作者（用户）id
                articleDetails: {}, // 文章详情
                isFocused: false, // 输入框是否聚焦 默认未聚焦
                dialogVisible: false, // 登录弹窗
                isActive: false,
                commentContent: '',
                commentList: [], // 评论列表
                commentTotal: 0, // 总评论
                currentPage: 1, // 当前页码
                pageSize: 5, // 每页显示条数
                currentRow: null,
                timer: null, // 延时器
                isLike: false, // 是否点赞
                isFollow: false, // 是否关注
            }
        },

        mounted() {
            // 获取文章id和作者id
            if (this.$route.query && this.$route.query.articleId && this.$route.query.userId) {
                this.articleId = this.$route.query.articleId
                this.userId = this.$route.query.userId
                this.findArticleDetails().then(() => {
                    this.findViewCount() // 查询浏览量
                    if (this.isLogin) {
                        this.$refs.articleCommentList.findArticleCommentList() // 查询文章评论列表
                        this.$refs.articleCommentList.findCommentTotalCount() // 查询所有父子评论总数
                    }
                })
            } else {
                this.$router.back(-1) // 返回上一页
            }

            // 获取文章点赞状态、获取文章评论列表(需要先登录，如果用户没有登录，就不用调这个接口)
            if(this.isLogin) {
                this.findIsLike()
                this.findIsFollow()
            }
        },

        methods: {
            // 删除评论接口回调
            delComment(commentId) {
                delComment({ commentId, articleId: this.articleId}).then((res) => {
                    if (res.code === 200) {
                        this.handleDel(commentId, this.commentList)
                        Utils.popUpMsg('success', '删除成功', 1000)
                        this.commentTotal --
                    }
                })
            },

            // 删除评论
            handleDel(commentId, data) {
                data.forEach(item => {
                    if (item.commentId === commentId) {
                        data.splice(this.commentList.indexOf(item), 1)
                    }

                    if (item.children && item.children.length > 0) {
                        this.handleDel(commentId, item.children)
                    }
                })
            },

            // 获取文章评论接口回调
            findCommentList() {
                let params = {
                    articleId: this.articleId,
                    pageSize: this.pageSize,
                    currentPage: this.currentPage
                }

                this.loading = true
                getCommentList(params).then(res => {
                    this.loading = false
                    if (res.code == 200) {
                        let data = this.commentList.concat(...res.data.rows)
                        this.commentList = this.handleCommentData(data.map(x => { x.children = []; return x; }))
                        this.commentTotal = res.data.total
                    }
                }).catch(err => {
                    this.loading = false
                })
            },

            // 处理评论数据
            handleCommentData(comments) {
                // 创建评论ID到评论对象的映射
                const commentMap = new Map()
                const rootComments = []

                comments.forEach(c => {
                    c.commentId = String(c.commentId)
                    c.parentId  = c.parentId === null ? null : String(c.parentId)
                })
                
                // 第一次遍历：创建所有节点的映射，并找出所有一级评论
                comments.forEach(comment => {
                    if (comment.parentId === '0' || comment.parentId === '') {
                        comment.parentId = null;
                    }

                    const node = { ...comment, children: [] }
                    commentMap.set(String(comment.commentId), node)
                    
                    if (comment.parentId === null) {
                        rootComments.push(node)
                    }
                })
                
                // 第二次遍历：构建评论树，但将所有多级评论提升为二级
                comments.forEach(comment => {
                    if (comment.parentId !== null) {
                        const currentNode = commentMap.get(String(comment.commentId))
                        const parentNode  = commentMap.get(String(comment.parentId))
                        
                        if (parentNode) {
                            // 如果父评论是一级评论，直接添加到其children
                            if (parentNode.parentId === null) {
                                parentNode.children.push(currentNode);
                            } else {
                                // 如果父评论不是一级评论（即父评论本身是二级或多级评论）
                                // 那么找到这个父评论所属的一级评论
                                let rootParent = parentNode;
                                while (rootParent.parentId !== null) {
                                    rootParent = commentMap.get(rootParent.parentId);
                                }
                                // 将当前评论添加到一级评论的children中（提升为二级评论）
                                rootParent.children.push(currentNode);
                            }
                        }
                    }
                });
                
                return rootComments;
            },

            // 发送评论（子级和父级）
            sendComment(content, fileList, replyContent, parent) {
                let picUrls = fileList.map(x => x.url).join(',')
                let data = {
                    articleId: this.articleId,
                    uid: this.userId,
                    content: content ? content : replyContent,
                    picUrls: picUrls,
                    parentId: replyContent ? parent.commentId : null,
                }
                commentArticle(data).then(res => {
                    if (res.code === 200) {
                        Utils.popUpMsg('success', '评论成功', 1000)
                        if(content) {
                            this.commentList = []
                            this.findCommentList()
                        }
                        if(replyContent) {
                            this.commentList = []
                            this.findCommentList()
                        }
                    } else {
                        Utils.popUpMsg('error', res.msg, 3000)
                    }
                }).catch(err => {
                    this.loading = false
                })
            },

            // 回复子评论
            clickReplyComment(row) {
                this.currentRow = row
            },

            // 展示全部评论
            clickMoreComment() {
                this.currentPage ++
                this.findCommentList()
            },

            // 展示全部回复
            clickAllReply(item) {
            },

            // 删除字段
            delFiled(commentId, data) {
                for (let i = 0; i < data.length; i++) {
                    if (data[i].commentId === commentId) {
                        data.splice(i, 1)
                        break
                    }
                }

                return data
            },

            // 查询用户是否关注过
            findIsFollow() {
                findFollowState({followId: this.userId}).then(res => {
                    if (res.code == 200) {
                        this.isFollow = res.data
                    } else {
                        Utils.popUpMsg('error', err.msg, 3000)
                    }
                }).catch(err => {
                })
            },

            // 关注用户接口
            followUser() {
                follow({followId: this.userId}).then(res => {
                    if (res.code == 200) {
                        this.isFollow = true
                        Utils.popUpMsg('success', '关注成功', 1000)
                        this.$store.dispatch('user/getFriendList')
                        this.findArticleDetails()
                    } else {
                        Utils.popUpMsg('error', '关注失败', 3000)
                    }
                }).catch(err => {
                })

            },

            // 取消关注
            cancelFollowUser() {
                cancelFollow({followId: this.userId}).then(res => {
                    if (res.code == 200) {
                        this.isFollow = false
                        Utils.popUpMsg('success', '取消关注', 1000)
                        this.$store.dispatch('user/getFriendList')
                        this.findArticleDetails()
                    } else {
                        Utils.popUpMsg('error', '取消关注失败', 3000)
                    }
                }).catch(err => {
                    Utils.popUpMsg('error', '取消关注失败', 3000)
                })
            },

            // 关注
            handleFollow() {
                if (!this.isLogin) {
                    this.handleShowLoginDialog()
                    return
                }

                this.followUser()
            },

            // 私信
            async handlePrivateMessage() {
                if (!this.isLogin) {
                    this.handleShowLoginDialog()
                    return
                }

                // 获取最新好友列表
                try {
                    await this.$store.dispatch('user/getFriendList')
                } catch (error) {
                    Utils.popUpMsg('error', '获取好友列表失败', 3000)
                    return
                }

                // 查看该篇文章作者是否与本人存在互关
                const hasFriendList = this.friendList.filter(item => item.userId === this.articleDetails.userId)

                if (hasFriendList.length > 0) {
                    this.$store.commit('user/setNoReadMsgList', this.noReadMsgList.filter(item => item.senderId !== this.friendList[0].userId))
                    this.$store.commit('user/setNoReadMsgCount', this.noReadMsgList.filter(item => item.senderId !== this.friendList[0].userId).length)
                    this.$store.commit('user/setCurrentFriend', this.articleDetails)

                    // 更新好友列表未读消息和数量
                    this.$store.dispatch('user/updateFriendMsgState', { senderId: this.articleDetails.userId })
                    this.$store.commit('user/setNoReadCount', this.currentFriend)
                    this.$router.push({
                        path: `/privateMessage`,
                        query: {
                            userId: this.articleDetails.userId
                        }
                    })
                } else {
                    Utils.popUpMsg('warning', '对方还未回关您', 3000)
                    return
                }
            },

            // 查询验证码
            findCaptcha() {
                getCaptcha().then(res => {
                    this.captchaId = res.data.captchaId
                    this.captchaSvg = res.data.captchaUrl
                })
            },

            // 查询添加文章观看次数
			findViewCount() {
                if (!this.isLogin) return
                this.timer = setTimeout(() => {
                    addViewCount({articleId: this.articleId}).then(res => {
                        if (res.code === 200) {
                            this.findArticleDetails()
                        }
                    })
                }, 1000 * 20)
			},

            // 查询文章详情
            findArticleDetails() {
                return new Promise((resolve, reject) => {
                    let params = {
                        articleId: this.articleId,
                        userId: this.userId
                    }

                    this.$store.dispatch('articleManage/getArticleDetail', params).then(res => {
                        this.articleDetails = res.data
                        resolve(res)
                    }).catch(err => {
                        reject(err)
                    })
                })
            },

            // 查询用户是否给文章点赞
            findIsLike() {
                getLikeArticleState({articleId: this.articleId}).then(res => {
                    if (res.code == 200) {
                        this.isLike = res.data
                    } else {
                        Utils.popUpMsg('error', err.msg, 3000)
                    }
                })
            },

            // 点赞回调
            handleLikeCount() {
                if (!this.isLogin) {
                    this.dialogVisible = true
                    return
                }

                if (this.userId == this.userInfo.id) {
                    Utils.popUpMsg('error', '把赞留给读者吧~', 1000)
                    return
                }

                likeArticle({articleId: this.articleId}).then(res => {
                    if (res.code === 200) {
                        this.isLike = !this.isLike
                        Utils.popUpMsg('success', this.isLike ? '点赞成功' : '取消点赞', 1000)
                        this.findArticleDetails()
                    } else {
                        Utils.popUpMsg('error', '点赞失败', 3000)
                    }
                })
            },

            // 展示登录弹窗
            handleShowLoginDialog() {
                this.findCaptcha()
                this.dialogVisible = true
            },

            // 关闭登录弹窗
            cancelLoginDialog() {
				this.dialogVisible = false
			},

            // 聚焦时输入框
            handleFocus() {
                this.isFocused = true
            },

            // 失焦时输入框
            handleBlur() {
                this.isFocused = false
            },
        },

        beforeDestroy() {
            clearTimeout(this.timer)
        }
    }
</script>

<style lang="scss">
    .previewContainer img {
        max-width: 100%;
        font-size: 1rem;
    }
</style>

<style lang="scss" scoped>
    @import "@/assets/style/variable.module.scss";

    @media screen and (max-width: 750px) {
        .author-info {
            display: none;
        }

    .leaveSpace {
		padding-left: 0;
		padding-right: 0;
	}
        
    }
    
    @media screen and (min-width: 750px) {
        .backHome {
            display: none;
        }

        .leaveSpace {
            padding-left: 10px;
            padding-right: 10px;
        }
    }

    .mainColor:hover {
        color: $mainColor;
    }

    .guanzhu:hover {
        background-color: #1171ee;
    }

    .follow:hover {
        background-color: #1171ee;
    }

    .sixin:hover {
        background-color: #e8f2ff;
    }

    .hover {
        color: #1e9fff;
        
    }

    .isFocused {
        display: flex;
        position: relative;
        background-color: #ffffff;
        font-size: 14px;
        width: 100%;
        border-radius: 5px;
        margin-left: 15px;
        height: 150px;
        border: 1px solid #1e80ff;
    }

    .emoji-icon:hover {
        color: #1e80ff;
    }

    .follow {
        overflow: hidden;
        white-space: nowrap;
        transition: all 0.8s ease-out;
    }
    
    .sixin {
        overflow: hidden;
        white-space: nowrap;
        transition: all 0.8s ease-out;
    }
</style>
